package com.theaf.core.rmq;

import com.theaf.core.utils.SpringUtils;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息发送帮助类
 */
public class MQSendHelper {
    private MQSendHelper(){}

    static{
        try {
            init();
        } catch (Exception e) {
            try {
                init();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
    private static MessageSender messageSender;

    public static void init() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = (ConnectionFactory) SpringUtils.getBean(ConnectionFactory.class);
        //初始化发送者
        MQAccessBuilder mqAccessBuilder = new MQAccessBuilder(connectionFactory);
        messageSender = mqAccessBuilder.buildMessageSender();
    }

    /**
     * 发送简单消息
     * @param tag
     * @param userMessage
     * @return
     */
    public static void send(String tag,Object userMessage,long delay) throws Exception{
        sendRpc(tag,userMessage,null,delay);
    }

    /**
     * 发送广播消息
     * @param tag
     * @param userMessage
     * @return
     */
    public static void sendFanout(String tag,Object userMessage,long delay)throws Exception {
        messageSender.send(userMessage,tag,"",null,delay);
    }

    /**
     * 发送简单消息，带回调功能
     * @param tag
     * @param userMessage
     * @param rpcCallBack
     * @param delay
     * @throws Exception
     */
    public static void sendRpc(String tag,Object userMessage,RpcCallBack rpcCallBack,long delay) throws Exception{
        messageSender.send(userMessage,"",tag,rpcCallBack,delay);
    }

    /**
     * 异步本地服务调用
     * @param bean
     * @param methode
     * @param delay
     * @param ars
     * @throws Exception
     */
    public static void invoke(String bean,String methode,long delay,Object... ars)throws Exception {
        Object[] mes = new Object[]{bean,methode,ars};
        messageSender.send(mes,"", MQAccessBuilder.INVOKE_QUEUE,null,delay);
    }
}
